package vn.gq.udv.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

public class SimpleDownload {
	
	private Context context;
	private ProgressDialog progressDialog;
	private String path;
	private String packageName;
	
	public SimpleDownload(Context ctx, String packageName) {
		context = ctx;
		this.packageName = packageName;
	}
	
	public void start(String url, ICallBack callback) {
		progressDialog = ProgressDialog.show(context, "Downloading", "");
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setTitle("Downloading");
		progressDialog.setMessage("Connecting...");
		DownloadAsyncTask dl = new DownloadAsyncTask(callback);
		dl.execute(url);
	}
	
	public String getDownloadPath() {
		String inPath = "/data/data/"+packageName;
		File sdcard = Environment.getExternalStorageDirectory();
		String exPath = sdcard.getAbsolutePath() + File.separator + "download";
		if (GQUtils.sdCardIsReady()) {
			return exPath;
		}
		return inPath;
	}
	
	public class DownloadAsyncTask extends AsyncTask<String, Integer, Void> {
		
		private boolean hasError = false;
		private ICallBack callback;
		
		public DownloadAsyncTask() {}
		
		public DownloadAsyncTask(ICallBack callback) {
			this.callback = callback;
		}
		
		@Override
		protected Void doInBackground(String... params) {
			String inet = params[0];
			InputStream is = null;
			URLConnection URLConn = null;
			URL fileUrl;
			try {
				fileUrl = new URL(params[0]);
				URLConn = fileUrl.openConnection();
				if (!URLConn.getContentType().contains("text/html")) {
					is = URLConn.getInputStream();
					String fileName = inet.substring(inet.lastIndexOf("/") + 1);
					if (fileName.equals("")) fileName = "downloadTemp";
					path = getDownloadPath() + File.separator + fileName;
					IOHelper.writeFile(is, path, new IProgressStatus() {
						
						@Override
						public void onPostProgress(int value) {
							publishProgress(value);
						}
					});
				}
				hasError = true;
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			float sizeInKB = values[0] / 1024;
			if (sizeInKB > 1024) {
				float sizeInMB = sizeInKB / 1024;
				progressDialog.setMessage(sizeInMB + " MB");
			} else {
				progressDialog.setMessage(sizeInKB + " KB");
			}
		}

		@Override
		protected void onPostExecute(Void result) {
			if (progressDialog != null) progressDialog.dismiss();
			if (callback != null) {
				callback.onOK(hasError, result, path);
			}
			super.onPostExecute(result);
		}
		
	}
}
